// ajax:前后端交互，问后端要数据，要结果。
// 参数：
//    请求地址
//    请求方式
//    请求参数
//    回调函数（后端响应回来后，要调的回调函数，也就是前端做的事情）

// 返回值：XMLHttpRequest对象

function ajax2308(url, method, data, cb) {
    let xhr = new XMLHttpRequest();

    // if(method.toLowerCase()=="get"){
    //     xhr.open(method, url+"?"+data);
    // }else{
    //     xhr.open(method, url);
    // }

    let urlAndData = url;
    if (method.toLowerCase() == "get") {
        urlAndData += "?" + data;
    }
    xhr.open(method, urlAndData);

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let obj = JSON.parse(xhr.responseText);
            cb(obj);
        }
    };

    if (method.toLowerCase() == "post") {
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(data);
    } else {
        xhr.send();
    }

    return xhr;
}

// 封装ajax（把参数写成json对象，参数为json对象时，经常会叫做配置项）：
function ajax230802(options) {
    // 1、配置项（参数）的默认值
    let defaultObj = {
        url: "#",
        method: "get",
        data: {},
        cb: null,
    };

    let resultObj = {};
    for (let key in defaultObj) {
        if (options[key] != undefined) {
            resultObj[key] = options[key];
        } else {
            resultObj[key] = defaultObj[key];
        }
    }

    let xhr = new XMLHttpRequest();

    let urlAndData = resultObj.url;
    if (resultObj.method.toLowerCase() == "get") {
        urlAndData += "?" + resultObj.data;
    }
    xhr.open(resultObj.method, urlAndData);

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let obj = JSON.parse(xhr.responseText);
            resultObj.cb && typeof resultObj.cb === "function" && resultObj.cb(obj);
        }
    };

    if (resultObj.method.toLowerCase() == "post") {
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(resultObj.data);
    } else {
        xhr.send();
    }

    return xhr;
}

// 封装ajax，用Promise
function ajaxUsePromise(options) {
    // 1、配置项（参数）的默认值
    let defaultObj = {
        url: "#",
        method: "get",
        data: {},
    };

    let resultObj = {};
    for (let key in defaultObj) {
        if (options[key] != undefined) {
            resultObj[key] = options[key];
        } else {
            resultObj[key] = defaultObj[key];
        }
    }

    let xhr = new XMLHttpRequest();

    let urlAndData = resultObj.url;
    if (resultObj.method.toLowerCase() == "get") {
        urlAndData += "?" + resultObj.data;
    }
    xhr.open(resultObj.method, urlAndData);

    let p = new Promise(function (resolve, reject) {
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let obj = JSON.parse(xhr.responseText);
                    resolve && typeof resolve == "function" && resolve(obj);
                } else {
                    reject();
                }
            }
        };
    });

    if (resultObj.method.toLowerCase() == "post") {
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(resultObj.data);
    } else {
        xhr.send();
    }

    return p;
}

// 调用：
// ajaxUsePromiseI({

// }).then((obj)=>{

// })

function ajaxUsePromise02(options) {
    return new Promise(function (resolve, reject) {
        // 1、配置项（参数）的默认值
        let defaultObj = {
            url: "#",
            method: "get",
            data: "",
        };

        let resultObj = {};
        for (let key in defaultObj) {
            if (options[key] != undefined) {
                resultObj[key] = options[key];
            } else {
                resultObj[key] = defaultObj[key];
            }
        }

        let xhr = new XMLHttpRequest();

        let urlAndData = resultObj.url;
        if (resultObj.method.toLowerCase() == "get") {
            urlAndData += "?" + resultObj.data;
        }
        xhr.open(resultObj.method, urlAndData);

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (/^2\d{2}$/.test(xhr.status)) {
                    let obj = JSON.parse(xhr.responseText);
                    resolve && typeof resolve == "function" && resolve(obj);
                } else {
                    // reject && typeof reject == "function" && reject("出错了,"+xhr.status);

                    reject && typeof reject == "function" && reject("出错了," + xhr.statusText);
                }
            }
        };

        // if (resultObj.method.toLowerCase() == "post") {

        // } else {
        //     xhr.send();
        // }
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(resultObj.data);
    });
}
